import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:rembercount/controller/authLoginController.dart';

class CountController extends GetxController {
  final categoryController = TextEditingController();
  final noteController = TextEditingController();
  final amountController = TextEditingController();
  final dateController = TextEditingController();
  Authlogincontroller authlogincontroller = Get.find<Authlogincontroller>();
  final category = ''.obs;
  final amount = 0.obs;
  final categoryList = ['收入', '支出'].obs;
  final categoryIndex = 0.obs;
  final amountList = [0, 0].obs;
  final countType = 'zhi'.obs; // 新增：默认为支出
  var stages = Rx<int?>(null); // Initialize as null by default
  var firstPaymentDate = DateTime.now().obs; // 新增：首次还款日期
  var reFund;
  var walletAccount = TextEditingController();
  var assetTypes = [];

  final dio = Dio(
    BaseOptions(
      baseUrl: const String.fromEnvironment(
        'BASE_URL',
        defaultValue: "http://localhost:8080",
      ),
    ),
  );

  // 计算分期付款日期列表
  List<Map<String, dynamic>> calculateInstallmentDates() {
    if (stages.value == null || stages.value! <= 0) {
      return [];
    }

    List<Map<String, dynamic>> dates = [];
    // 安全地解析金额
    String cleanAmount = amountController.text.replaceAll(
      RegExp(r'[^\d.]'),
      '',
    );
    if (cleanAmount.split('.').length > 2) {
      cleanAmount =
          cleanAmount.split('.')[0] +
          '.' +
          cleanAmount.split('.').sublist(1).join('');
    }
    double amount = double.tryParse(cleanAmount) ?? 0;
    double amountPerStage = amount / stages.value!;

    for (int i = 0; i < stages.value!; i++) {
      // 计算每期的日期（每月一次）
      DateTime paymentDate = DateTime(
        firstPaymentDate.value.year,
        firstPaymentDate.value.month + i,
        firstPaymentDate.value.day,
      );

      dates.add({
        'stage': '第${i + 1}期',
        'date': paymentDate.toIso8601String(),
        'amount': amountPerStage.toStringAsFixed(2),
        'status': 'pending', // 可以添加状态：pending, paid, overdue
      });
    }

    return dates;
  }

  String oneStafesAmount(var amounta, var stagesa) {
    return (amounta / stagesa).toString();
  }

  Future<void> finishState(var record) async {
    List stagesList = record['stagesList'];
    for (var element in stagesList) {
      element['isBack'] = true;
      element['backTime'] = DateFormat("yyyy-MM-dd").format(DateTime.now());
    }
    record['stagesList'] = stagesList;
    await edit(record);
  }

  Future<Map<String, dynamic>> saveCount() async {
    var installmentDates = calculateInstallmentDates();
    // 清理金额字符串
    String cleanAmount = amountController.text.replaceAll(
      RegExp(r'[^\d.]'),
      '',
    );
    if (cleanAmount.split('.').length > 2) {
      cleanAmount =
          cleanAmount.split('.')[0] +
          '.' +
          cleanAmount.split('.').sublist(1).join('');
    }
    double amount = double.tryParse(cleanAmount) ?? 0;

    var res = await dio.post(
      "/saveCount",
      data: {
        'category': categoryController.text,
        'amount': amount,
        'date': dateController.text,
        'note': noteController.text,
        'creater': authlogincontroller.emailController.text,
        'countType': countType.value,
        'stages': stages.value,
        'reFund': reFund,
        'firstPaymentDate': firstPaymentDate.value.toIso8601String(),
        'installmentDates': installmentDates, // 添加分期付款日期列表,
        'walletAccount': walletAccount.text,
      },
    );

    return res.data;
  }

  Future<List> getAssetType() async {
    var res = await dio.post('/getAssetType',data: {'creater': authlogincontroller.emailController.text});
    print('getAssetType:$res');
    return res.data['data'];
  }

  Future<Map<String, dynamic>> reset() async {
    var res = await dio.post(
      "/reset",
      data: {
        'creater': authlogincontroller.emailController.text,
        // 添加分期付款日期列表
      },
    );
    // print(res.data);
    return res.data;
  }

  Future<Map<String, dynamic>> edit(Map item) async {
    var res = await dio.post("/saveCount", data: item);
    return res.data;
  }

  Future<Map<String, dynamic>> saveAssetType() async {
    var res = await dio.post(
      "/saveAssetType",
      data: {
        'assetTypes': assetTypes,
        'creater': authlogincontroller.emailController.text,
      },
    );
    return res.data;
  }

  Future<List> getCount(String? email) async {
    var res = await dio.get("/getCount/$email");
    // print(res.data);
    return res.data['data'];
  }

  Future<Map<String, dynamic>> deleteCount(var delItem) async {
    var res = await dio.post("/deleteCount", data: delItem);
    return res.data;
  }

  String check(String? count, String? category) {
    print('count:${count}');
    print('category:${category}');
    String isFailMsg = "";

    if (count == null || category == null) {
      isFailMsg = "请输入分类和金额";
    } else if (count.isEmpty || category.isEmpty) {
      isFailMsg = "请输入分类和金额";
    } else {
      final parsedCount = double.tryParse(count);
      if (parsedCount == null) {
        isFailMsg = "金额格式错误";
      } else if (parsedCount < 0) {
        isFailMsg = "金额不能小于0";
      }
    }
    return isFailMsg;
  }

  Future<Map<String, dynamic>> updateStage(
    String recordId,
    Map<String, dynamic> stage,
  ) async {
    var res = await dio.post(
      "/updateStage",
      data: {'recordId': recordId, 'stage': stage},
    );
    return res.data;
  }
}
